package com.yswy.theater.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.obs.services.model.PutObjectResult;
import com.yswy.common.utils.*;
import com.yswy.common.utils.videoTpGif.FfmpegUtil;
import com.yswy.theater.entity.TheaterPlay;
import com.yswy.theater.entity.TheaterPlayBindType;
import com.yswy.theater.entity.TheaterPlayGather;
import com.yswy.theater.mapper.TheaterPlayMapper;
import com.yswy.theater.service.TheaterPlayBindTypeService;
import com.yswy.theater.service.TheaterPlayGatherService;
import com.yswy.theater.service.TheaterPlayService;
import com.yswy.theater.vo.req.AddTheaterPlay;
import com.yswy.theater.vo.req.AddTheaterPlayCsj;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;


@Slf4j
@Service
public class TheaterPlayServiceImpl extends ServiceImpl<TheaterPlayMapper, TheaterPlay>
        implements TheaterPlayService {
    @Autowired
    private HuaWeiYunOBSUtil huaWeiYunOBSUtil ;
    @Autowired
    private TheaterPlayGatherService theaterPlayGatherService ;
    @Autowired
    private TheaterPlayBindTypeService theaterPlayBindTypeService ;
    @Override
    public Integer updateLikeNum(long playId) {
        TheaterPlay theaterPlay = getById(playId);
        if (theaterPlay != null){
            theaterPlay.setLikeNum(theaterPlay.getLikeNum()+1);
            updateById(theaterPlay);
        }
        return theaterPlay.getLikeNum();
    }

    @Override
    public void updateCollectNum(Long playId) {
        TheaterPlay theaterPlay = getById(playId);
        if (theaterPlay != null){
            theaterPlay.setCollectNum(theaterPlay.getCollectNum()+1);
            updateById(theaterPlay);
        }
    }


    @Override
    @Transactional
    public void addTheaterPlayByCsj(List<AddTheaterPlayCsj> addTheaterPlayCsjs) {
        for (AddTheaterPlayCsj a:addTheaterPlayCsjs) {
            try {

                TheaterPlay theaterPlay = getOne(new LambdaQueryWrapper<TheaterPlay>().eq(TheaterPlay::getCsjPlayId , a.getPlayId()));
                if (theaterPlay == null){
                    theaterPlay = TheaterPlay.builder()
                            .playName(a.getPlayName())
                            .playMsg(a.getPlayMsg())
                            .playTitleUrl(a.getPlayTitleUrl())
                            .playType(0)
                            .isShow(1)
                            .sex(0)
                            .likeNum(0)
                            .collectNum(0)
                            .zyType(3)
                            .isAdUnlock(false)
                            .unlockSpecies(10)
                            .defUnlockNum(5)
                            .unlockType(0)
                            .csjPlayId(a.getPlayId())
                            .episodes(a.getEpisodes())
                            .build();
                    save(theaterPlay);

                    List<TheaterPlayGather> theaterPlayGathers = new ArrayList<>();
                    List<TheaterPlayBindType> theaterPlayBindTypes = new ArrayList<>();

                    theaterPlayBindTypes.add(TheaterPlayBindType.builder()
                            .typeId(2L)
                            .theaterPlayId(theaterPlay.getId())
                            .sortId(0).build());
                    theaterPlayBindTypes.add(TheaterPlayBindType.builder()
                            .typeId(4L)
                            .theaterPlayId(theaterPlay.getId())
                            .sortId(0).build());
                    for (int i = 1; i <= a.getEpisodes(); i++) {
                        theaterPlayGathers.add(TheaterPlayGather.builder()
                                .episodes(i)
                                .playTitleUrl(a.getPlayTitleUrl())
                                .theaterPlayId(theaterPlay.getId())
                                .build());
                    }
                    theaterPlayGatherService.saveBatch(theaterPlayGathers);
                    theaterPlayBindTypeService.saveBatch(theaterPlayBindTypes);
                }else {
                    if (theaterPlay.getEpisodes() !=a.getEpisodes()  ){
                        //修改短剧集数
                        TheaterPlayGather theaterPlayGather = theaterPlayGatherService
                                .getOne(new LambdaQueryWrapper<TheaterPlayGather>()
                                        .orderByDesc(TheaterPlayGather::getEpisodes)
                                        .last("limit 1"));
                        List<TheaterPlayGather> theaterPlayGathers = new ArrayList<>();
                        for (int i = (theaterPlayGather.getEpisodes()+1); i <= a.getEpisodes(); i++) {
                            theaterPlayGathers.add(TheaterPlayGather.builder()
                                    .episodes(i)
                                    .playTitleUrl(a.getPlayTitleUrl())
                                    .theaterPlayId(theaterPlay.getId())
                                    .build());
                        }
                        theaterPlayGatherService.saveBatch(theaterPlayGathers);

                    }
                    update(new LambdaUpdateWrapper<TheaterPlay>()
                            .eq(TheaterPlay::getCsjPlayId ,a.getPlayId())
                            .eq(TheaterPlay::getPlayName , a.getPlayName())
                            .eq(TheaterPlay::getPlayMsg , a.getPlayMsg())
                            .eq(TheaterPlay::getPlayTitleUrl , a.getPlayTitleUrl())
                            .eq(TheaterPlay::getPlayName , a.getPlayName()));
                }
            }catch (Exception e){

            }


        }
    }


    @Override
    public void addTheaterPlay(AddTheaterPlay addTheaterPlay) {
        String playName = addTheaterPlay.getPlayPath();
        String playMsg = addTheaterPlay.getPlayPath();
        String playPath = "C:\\Users\\mxy\\Desktop\\"+addTheaterPlay.getPlayPath();
        File file = new File(playPath);
        if (!file.exists()) {
            return ;
        }
        List<String> fileNames = new ArrayList<>();
        FileSuffix.getFileNames(file, fileNames);


//        File file = new File(playPath);
//        String[] fileNames = file.list();
//        SortFileName(fileNames);
        fileNames = fileNames.stream().sorted(new AlphanumComparator()).collect(Collectors.toList());
        for (String s : fileNames) {
            System.out.println(s);
        }

        TheaterPlay theaterPlay = getOne(new LambdaQueryWrapper<TheaterPlay>().eq(TheaterPlay::getPlayName , playName));
        if (theaterPlay == null){
            theaterPlay = TheaterPlay.builder()
                    .playName(playName)
                    .playMsg(playMsg)
                    .playType(addTheaterPlay.getPlayType())
                    .isShow(1)
                    .episodes(fileNames.size())
                    .build();
            save(theaterPlay);
        }else {
            return;
        }



        for (int i = 0; i <fileNames.size()  ; i++) {
            try {
                String filename = fileNames.get(i);
//                System.out.println(filename);
                TheaterPlayGather theaterPlayGather = new TheaterPlayGather();
                theaterPlayGather.setTheaterPlayId(theaterPlay.getId());
                theaterPlayGather.setEpisodes(i+1);
//                int c = i-1;
//                String s = ""+i+"-加微信17023061052,免费送网剧一部！.mp4" ;
                String filePath = playPath+"\\"+filename ;

                String[] filePaths = filename.split("\\.");





                System.out.println(filePath+"开始上传");
                File upfile =  new File(filePath) ;
                String mp4url = huaWeiYunOBSUtil.largeUpload(UUID.randomUUID() + "."+filePaths[1]
                        ,"play/"+theaterPlay.getId() ,  upfile);
                theaterPlayGather.setPlayUrl(mp4url);
//                InputStream filePathIn =  new FileInputStream(new File(filePath));
//                PutObjectResult newResult = huaWeiYunOBSUtil.upload( UUID.randomUUID() + "."+filePaths[1] , "play/"+theaterPlay.getId(),filePathIn);
//                theaterPlayGather.setPlayUrl(newResult.getObjectUrl());
                System.out.println(filename+"上传完成  " + mp4url);


                String titlePath  = "C:\\Users\\mxy\\Desktop\\temp\\"+UUID.randomUUID()+".jpg" ;
                if (i == 0){
                    FfmpegUtil.videoScreenshot(filePath ,"00:00:00"  ,titlePath);
                }else {
                    FfmpegUtil.videoScreenshot(filePath ,"00:00:10"  ,titlePath);
                }

                InputStream titlePathIn =  new FileInputStream(new File(titlePath));
                PutObjectResult titleResult = huaWeiYunOBSUtil.upload( UUID.randomUUID() + ".jpg" , "play/"+theaterPlay.getId(),titlePathIn);
                theaterPlayGather.setPlayTitleUrl(titleResult.getObjectUrl());

                if (i == 0){
                    theaterPlay.setPlayTitleUrl(titleResult.getObjectUrl());
                    updateById(theaterPlay);
                }
//                File file1 = new File(titlePath);
//                file1.delete();
//                upfile.delete();
                theaterPlayGatherService.save(theaterPlayGather);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        System.out.println(playPath+"----------------------------------------------------------------------------------------------完成");
    }

    public static void main(String[] args) {

        String playPath = "C:\\Users\\mxy\\Desktop\\2023最新1\\2023最新7\\百亿赘婿在身边";
        File file = new File(playPath);
        if (!file.exists()) {
            return ;
        }
        List<String> fileNames = new ArrayList<>();
        FileSuffix.getFileNames(file, fileNames);
        fileNames = fileNames.stream().sorted(new AlphanumComparator()).collect(Collectors.toList());
//        System.out.println(fileNames.stream().sorted(new AlphanumComparator()).collect(Collectors.joining(" ")));

        for (String s:fileNames
             ) {
            System.out.println(s);
        }
//        orderByName(playPath);


    }


    private static String[] SortFileName(String[] Input){//void无返回值
        Arrays.sort(Input, new Comparator<String>() {
            @Override
            public int compare(String s1, String s2) {
                if (returnDouble(s1) < returnDouble(s2))
                    return -1;
                else if (returnDouble(s1) > returnDouble(s2))
                    return 1;
                else
                    return 0;
            }
            public double returnDouble(String str) {
                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < str.length(); i++) {
                    if (Character.isDigit(str.charAt(i)))
                        sb.append(str.charAt(i));
                    else if (str.charAt(i) == '.' && i < str.length() - 1 && Character.isDigit(str.charAt(i + 1)))
                        sb.append(str.charAt(i));
                    else break;
                }
                if (sb.toString().isEmpty())
                    return 0;
                else
                    return Double.parseDouble(sb.toString());
            }
        });
        if(Input==null){
            return new String[1];
        }else{
            return Input;
        }

    }

    public static void orderByName(String filePath) {
        File file = new File(filePath);
        File[] files = file.listFiles();
        List fileList = Arrays.asList(files);
        Collections.sort(fileList, new Comparator<File>() {
            @Override
            public int compare(File o1, File o2) {
                if (o1.isDirectory() && o2.isFile())
                    return -1;
                if (o1.isFile() && o2.isDirectory())
                    return 1;
                return o1.getName().compareTo(o2.getName());
            }
        });
        for (File file1 : files) {
            System.out.println(file1.getName());

        }
    }

}
